package com.mornd.gulimall.order.web.v1;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.mornd.gulimall.common.core.constant.ServerUrls;
import com.mornd.gulimall.common.core.exception.ServiceException;
import com.mornd.gulimall.common.core.result.AjaxResult;
import com.mornd.gulimall.order.entity.Order;
import com.mornd.gulimall.order.entity.vo.OrderConfirmVO;
import com.mornd.gulimall.order.entity.vo.OrderSubmitVo;
import com.mornd.gulimall.order.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import java.util.Map;

/**
 * @author: mornd
 * @dateTime: 2023/8/21 - 21:12
 */

@Slf4j
@Controller
public class RouteController {
    @Resource
    private IOrderService orderService;

    @GetMapping("/{page}.html")
    public String page(@PathVariable String page) {
        return page;
    }

    // http://order.gulimall.com/toTrade?1=1&2=2
    @GetMapping("/toTrade")
    public String toTrade(@RequestParam Map<String, String> params, Model model) {
        OrderConfirmVO orderConfirmVO = orderService.confirmOrder(params);
        model.addAttribute("orderConfirm", orderConfirmVO);
        return "confirm";
    }

    @ResponseBody
    @PostMapping("/submitOrder")
    public AjaxResult submitOrder(@RequestBody @Validated OrderSubmitVo orderSubmitVo) {
        try {
            Order order = orderService.submitOrder(orderSubmitVo);
            // 提交成功，去支付页面
            String url = ServerUrls.ORDER + "/pay?orderSn=" + order.getOrderSn();
            return AjaxResult.success((Object) url);
        } catch (Exception e) {
            log.error(e.getMessage());
            return AjaxResult.error("订单提交失败，" + e.getMessage());
        }
    }

    @GetMapping("/pay")
    public String payPage(@RequestParam("orderSn") String orderSn, Model model) {
        Order order = orderService.getOne(Wrappers.<Order>lambdaQuery().eq(Order::getOrderSn, orderSn));
        if (order == null) {
            throw new ServiceException("订单号" + orderSn + "不存在");
        }
        model.addAttribute("orderSn", order.getOrderSn());
        model.addAttribute("payPrice", order.getPayAmount());
        return "pay";
    }
}
